import 'package:scoped_model/scoped_model.dart';
import '../Models/product.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
// import 'package:firebase_database/firebase_database.dart';
// import 'package:firebase_database/ui/firebase_animated_list.dart';
// import 'package:firebase_core/firebase_core.dart';

class ScopedProduct extends Model {
  List<Product> _products = [];
//get 方法 复制一份
  List<Product> get products {
    return List.from(_products);
  }

  int _selectIndex;

  bool _showFavorite = false;

  bool get showFavorite {
    return _showFavorite;
  }

  int get selectIndex {
    return _selectIndex;
  }

  Product get selectProduct {
    notifyListeners();
    if (_selectIndex == null) {
      return null;
    }
    return _products[_selectIndex];
  }

  void fetchProduct() {
    http
        .get('https://flutter-cn.firebaseio.com/products.json')
        .then((http.Response response) {
      print(json.decode(response.body));
    });
  }

  void addProduct(Product product) {
    Map<String, dynamic> param = {
      'title': product.title,
      'description': product.description,
      'price': product.price
    };
    http
        .post('https://flutter-cn.firebaseio.com/products.json',
            body: json.encode(param))
        .then((http.Response response) {
      final Map<String, dynamic> responseData = json.decode(response.body);
      print('$responseData 数据');
      _products.add(Product(
          id: responseData['name'],
          title: product.title,
          description: product.description,
          imageURL: product.imageURL,
          price: product.price,
          isFavorite: false));
      notifyListeners();
    }).catchError((error) {
      print('$error错误');
    });

    //通知刷新
  }

  deleteProductWithIndex(index) {
    _products.removeAt(index);
    _selectIndex = null;
    notifyListeners();
  }

  updateProduct(Product product) {
    _products[_selectIndex] = product;
    print(_products.length);
    notifyListeners();
  }

  selectProductIndex(int index) {
    _selectIndex = index;
    print('选中' + index.toString());
  }

  changeFavorite() {
    final productFavorite = !selectProduct.isFavorite;
    final Product update = Product(
        title: selectProduct.title,
        description: selectProduct.description,
        imageURL: selectProduct.imageURL,
        price: selectProduct.price,
        isFavorite: productFavorite);
    updateProduct(update);
    _selectIndex = null;
    notifyListeners();
  }

  List<Product> get disPlayProducts {
    if (_showFavorite) {
      return List.from(
          _products.where((product) => product.isFavorite).toList());
    }
    return List.from(_products);
  }

  showFavoriteProduct() {
    _showFavorite = !_showFavorite;
    notifyListeners();
  }
}
